package com.sinosoft.mcp.client.mysql.config;

import org.springframework.ai.mcp.client.McpClient;
import org.springframework.ai.mcp.client.McpSyncClient;
import org.springframework.ai.mcp.client.transport.ServerParameters;
import org.springframework.ai.mcp.client.transport.StdioClientTransport;
import org.springframework.ai.mcp.spring.McpFunctionCallback;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zbc
 * @date 2025/3/30
 */
@Configuration
public class McpClientConfig {

    @Bean
    public List<McpFunctionCallback> functionCallbacks(List<McpSyncClient> mcpSyncClients) {
        List<McpFunctionCallback> list = new ArrayList<>();

        for (McpSyncClient mcpSyncClient : mcpSyncClients) {
            list.addAll(mcpSyncClient.listTools(null)
                    .tools()
                    .stream()
                    .map(tool -> new McpFunctionCallback(mcpSyncClient, tool))
                    .toList());
        }

        return list;
    }

    @Bean(destroyMethod = "close")
    public McpSyncClient mysqlMcpClient() {

        Map<String, String> env = new HashMap<>();
        env.put("MYSQL_HOST", "192.168.11.123");
        env.put("MYSQL_PORT", "32088");
        env.put("MYSQL_USER", "root");
        env.put("MYSQL_PASSWORD", "root");
        env.put("MYSQL_DATABASE", "test");

        var stdioParams = ServerParameters.builder("uvx")
                .args("mcp-server-mysql")
                .env(env)
                .build();

        var mcpClient = McpClient.sync(new StdioClientTransport(stdioParams))
                .requestTimeout(Duration.ofSeconds(10)).build();

        var init = mcpClient.initialize();

        System.out.println("MCP Initialized: " + init);

        return mcpClient;

    }

    //    @Bean(destroyMethod = "close")
    public McpSyncClient sqliteMcpClient() {

        var stdioParams = ServerParameters.builder("uvx")
                .args("mcp-server-sqlite", "--db-path",
                        getDbPath())
                .build();

        var mcpClient = McpClient.sync(new StdioClientTransport(stdioParams))
                .requestTimeout(Duration.ofSeconds(10)).build();

        var init = mcpClient.initialize();

        System.out.println("MCP Initialized: " + init);

        return mcpClient;

    }

    private static String getDbPath() {
        System.out.println(System.getProperty("user.dir"));
        return Paths.get(System.getProperty("user.dir"), "test.db").toString();
    }

}
